package com.app.stringgzip;


import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 字符串压缩
 *
 * @author ch
 * @date 2023/11/20 14:40
 */
@Slf4j
public class StringGzipUtil {


    /**
     * 字符串压缩
     *
     * @param str 原始字符串
     * @return 压缩后字符串
     */
    public static String zipString(String str) {
        if (str == null) {
            return null;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPOutputStream os = new GZIPOutputStream(bos)) {
            os.write(str.getBytes());
            os.close();
            bos.close();
            return bos.toString(StandardCharsets.ISO_8859_1.name());
        } catch (Exception ex) {
            log.error("压缩异常", ex);
            return str;
        }
    }

    /**
     * 解压ZIP字符串
     *
     * @param str 压缩后字符串
     * @return 原始字符串
     */
    public static String unzipString(String str) {
        if (str == null) {
            return null;
        }
        try (ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes(StandardCharsets.ISO_8859_1));
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPInputStream is = new GZIPInputStream(bis)) {

            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            return bos.toString();
        } catch (Exception ex) {
            log.error("解压异常", ex);
            return str;
        }
    }
}